<template>
	<div class="app-content">
		<div class="app-main border--all">
			<div class="plan-view plan-planning-list">
				<div class="plan-left border--right">
					<div class="view-title vi-view-title width-1" :class="{'view-title--margin-1-1':addPlanTagShow,'view-title--margin-1':!addPlanTagShow}">
						客群标签
						<el-icon class="float--right view-title-option" @click="addPlanTagShow = !addPlanTagShow">
							<Edit />
						</el-icon>
					</div>
					<div class="view-title vi-view-title view-title--clear-text-indent view-title--clear-border width-1 view-title--margin-3-1" v-if="addPlanTagShow">
						<el-input
							v-model="addPlanTag"
							placeholder="请输入客群标签"
						>
							<template #append>
								<el-button :icon="Plus" @click="addPlanTagEvent" />
							</template>
						</el-input>
					</div>
					<div class="view-tag" v-loading="planTagLoading">
						<!--					   <img src="/images/person-tag.png"/>-->
						<div class="flex view-tag-lists">
							<el-tag class="margin-5" v-for="(planTagList,index) in planTagLists" :key="planTagList" :type="planTagList.type" @close="deleteTag(index)" closable>{{planTagList.value}}</el-tag>
						</div>
					</div>
				</div>
				<div class="plan-right padding-20-lr">
					<div class="view-title vi-view-title width-1 view-title--margin-2-1">
						策案活动
						<el-icon class="float--right view-title-option" @click="addPlanList()">
							<Plus />
						</el-icon>
					</div>
					<div class="vi-container margin-t-20">
						<el-pagination class="float--right" background layout="prev, pager, next" v-if="activityPageLists.length>0" @current-change="loadActivityList" v-model:current-page="queryPager.page" :page-size="queryPager.size" :total="planTotal"/>
					</div>
					<div class="vi-plan-lists padding-20-lr" v-loading="activityListLoading">
						<div class="timelineProcessBox" v-for="(activityPageList,index) in activityPageLists" :key="activityPageList.id">
							<div class="timelineProcessBox-title" @click="openActivityModal(activityPageList)">{{index+1}}.{{activityPageList.copy_name}}</div>
							<div class="timelineProcessBox-time">{{timeFormat(activityPageList.start_time,"YYYY-MM-DD")}}—{{timeFormat(activityPageList.end_time,"YYYY-MM-DD")}}</div>
							<el-timeline class="timeline">
								<el-timeline-item
									class="lineitem"
									:class="activity.status != 0 ? 'active' : 'inactive'"
									v-for="(activity, index) in activityPageList.campaign_stage_list"
									:key="index"
									:timestamp="activity.generate_time"
									placement="top"
									@click="goEdit(activity)"
								>
								  <span class="timelineProcessBox-top-contents center-position-left">
									  <span class="timelineProcessBox-content">
									     引流目标：{{ activity.attraction_target }}
									  </span>
								  </span>
									<span class="timelineProcessBox-contents">
									<span class="timelineProcessBox-content">
									  {{ platform_type(activity.platform_type) }}
									</span>
								  </span>
								</el-timeline-item>
							</el-timeline>
							<div class="timelineProcessBox-border"></div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<el-dialog v-model="activityModal.visible" @close="closeActivityModal" width="800">
		<el-form :model="activityParams" :rules="activeityRules" ref="activityDialogRef" label-width="auto" v-loading="activityLoading" class="activity_dialog padding-20">
			<el-form-item label="活动名称" prop="copy_name">
				<el-input v-model="activityParams.copy_name" class="input-1" placeholder="请输入活动名称" />
			</el-form-item>
			<el-form-item label="活动日期范围" prop="time">
				<el-date-picker
					class="input-1"
					v-model="activityParams.time"
					type="datetimerange"
					range-separator="~"
					start-placeholder="开始时间"
					end-placeholder="结束时间"
				/>
			</el-form-item>
			<el-form-item label="总目标引流" prop="attraction_target">
				<el-input-number class="input-1 input-number" disabled v-model="activityParams.attraction_target" controls-position="right">
					<template #decrease-icon>
						<el-icon>
							<Minus />
						</el-icon>
					</template>
					<template #increase-icon>
						<el-icon>
							<Plus />
						</el-icon>
					</template>
				</el-input-number>
			</el-form-item>
			<div class="whole-parent-width">
				<el-form-item class="float--right">
					<el-button @click="addActivePhase">新增</el-button>
					<el-button type="primary" @click="deleteActivePhase">删除</el-button>
				</el-form-item>
			</div>
			<el-form-item>
				<active-phase-list :data="activityParams.campaign_stage_list" @select-change="activePhaseSelectChange" @attraction-change="activePhaseAttractionChange" @goChange="goAddPlaning" @goArticle="goArticle"></active-phase-list>
			</el-form-item>
			<div class="whole-parent-width">
				<el-form-item class="float--right">
					<el-button @click="closeActivityModal">取消</el-button>
					<el-button type="primary" @click="saveActivity">{{activityParams.id? "修改":"新增"}}</el-button>
				</el-form-item>
			</div>
		</el-form>
	</el-dialog>
</template>
<script setup lang="ts" name="bespoke-planning-list">
import { onMounted,onActivated, reactive, ref } from "vue";
import { Minus, Plus } from "@element-plus/icons-vue";
import { router, service,storage } from "/@/cool";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import {config} from '/@/utils/global'
import {
	getRandomInt,
	timeFormat,
	getRandomId,
	JsonArryToArray,
	setJsonArrayValue,
	bigToLower
} from "/@/utils/tools";
import { platform_type }from"/@/utils/dictionary";
import ActivePhaseList from "/$/planning/components/activePhaseList.vue";
import dayjs, { Dayjs } from "dayjs";
let route = useRoute();
const queryParams=reactive({
	id:<any>"",
	plan_name:<any>"",
	time:<any>[],
	number:0,
})
let planTotal = ref(0)
const queryPager=reactive({
	page:1,
	size:config.PAGE_SIZE,
})
//获取活动列表
let activityListLoading = ref(false);
let activityPageLists = ref<any[]>([]);
const getActivityList=async () =>{
	if(!queryParams.id){activityListLoading.value=false;return;}
	activityListLoading.value=true;
	let value = await service.campaign.info.getMySelect({...queryPager,plan_id:queryParams.id}).catch((error)=>{
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		activityListLoading.value=false;
		return;
	}).finally(()=>{
		activityListLoading.value=false;
	});
	planTotal.value = value.totalRow;
	let infoLists = bigToLower(value.records);
	activityPageLists.value=infoLists;
}
const loadActivityList=(value:number)=>{
	queryPager.page=value;
	getActivityList();
}
//新增一个策案计划id
let addPlanListLoading = ref(false)
let addPlanRequest = async()=>{
	if(queryParams.id){return;}
	let userInfo = storage.get("userInfo");
	queryParams.plan_name = userInfo.nickName+"的策案";
	let start_date = dayjs().format("YYYY-MM-DD");
	let end_date = dayjs().add(3, 'month').format('YYYY-MM-DD'); ;
	const params = {
		"plan_name": queryParams.plan_name,
		"plan_description": queryParams.plan_name,
		"start_date": start_date,
		"end_date": end_date,
		"attraction_target": 100,
		"creator": userInfo.id || "",
		"keywords": userInfo.nickName+"的关键词",
		"level": 1
	}
	addPlanListLoading.value=true;
	let values = await service.campaign.plan.add(params).catch((error)=>{
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		addPlanListLoading.value=false;
		return;
	}).finally(()=>{
		addPlanListLoading.value=false;
	});
	queryParams.id=values.id;
	return false;
}
let searchPlanRequest= async(callback?:Function)=>{
	activityListLoading.value=true;
	let userInfo = storage.get("userInfo");
	let result:any = await service.campaign.plan.page({creator:userInfo.id}).catch((error)=>{
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		activityListLoading.value=false;
		return;
	})
	let list = result.list?.length>0? result.list[0]:{}
	if(list?.id){
		queryParams.id = list.id;
		queryParams.plan_name = list?.plan_name || "";
		let startDate:any = list?.startDate || "";
		let endDate:any = list?.endDate || "";
		queryParams.time = [dayjs(startDate),dayjs(endDate)];
	}
	if(callback){
        callback(list);
	}else{
		activityListLoading.value=false;
	}
}
const addPlanList = async () =>{
	if(await addPlanRequest())return;
	openActivityModal();
}
//新增保存活动属性
const activityParams=reactive<any>({})
let activityLoading=ref(false);
const activityDialogRef= ref<any>()
//活动表单规则
const activeityRules = reactive<any>({
	copy_name: [
		{
			required: true,
			message: '请输入活动名称',
			trigger: 'change',
		},
	],
	time: [
		{
			required: true,
			message: '请选择开始时间和结束时间',
			trigger: 'blur',
		},
	],
	attraction_target:[
		{
			required: true,
			message: '请输入总目标引流',
			trigger: 'change',
		},
	],
});
const activityValidate=async (callback)=>{
	if (!activityDialogRef) return;
	await activityDialogRef.value.validate((valid, fields) => {
		if (valid) {
			callback(valid);
		} else {
			console.log('error submit!', fields)
		}
	})
}
const saveActivityRequest=(value:any)=>{
	if(value.id){
		return new Promise((resolve,reject)=>{
			service.campaign.info.update(value).then(()=>{
				resolve(value);
			},(error)=>{
				reject(error);
			})
		});
	}else{
		return service.campaign.info.add(value);
	}
}
const saveActivity=()=>{
	activityParams.plan_id = queryParams.id;
	activityParams.start_time = timeFormat(activityParams.time[0],"YYYY-MM-DD HH:mm:ss");
	activityParams.end_time = timeFormat(activityParams.time[1],"YYYY-MM-DD HH:mm:ss");
	activityParams.content = activityParams.copy_name;
	if(activityParams.campaign_stage_list.length<=0){
		ElMessage({
			message: "至少添加一个活动阶段",
			type: 'warning',
		})
		return;
	}
	activityValidate(async()=>{
		activityLoading.value=true;
		let value = await saveActivityRequest(activityParams).catch((error)=>{
			ElMessage({
				message: error.message || "加载失败",
				type: 'warning',
			})
			return;
		})
		activityParams.id = value.id;
		setJsonArrayValue(activityParams.campaign_stage_list,"campaign_id",activityParams.id);
		let activePhaseRequests:any[] = [];
		activityParams.campaign_stage_list.forEach((activePhaseList:any)=>{
			activePhaseRequests.push(saveActivePhase(activePhaseList));
		})
		await Promise.all(activePhaseRequests);
		activityLoading.value=false;
		getActivityList();
	})
}
//新增活动阶段
let addActivePhase = () =>{
	let value:any = {
		"select_index":getRandomId(),
		"id":"",
		"campaign_id": "",
		"generate_time": timeFormat(new Date(),"YYYY-MM-DD HH:mm:ss"),
		"attraction_target": 0,
		"platform_type": 1
	}
	activityParams.campaign_stage_list.push(value);
}
//选中活动阶段
let activePhaseSelectLists = ref([]);
const activePhaseSelectChange = (values) => {
	activePhaseSelectLists=values;
}
//删除活动阶段
const deleteActivePhase = async () =>{
	let activePhaseSelectIndex = JsonArryToArray(activePhaseSelectLists,"select_index");
	activityParams.campaign_stage_list = activityParams.campaign_stage_list.filter((item:any) => activePhaseSelectIndex.indexOf(item.select_index) == -1);
	activePhaseAttractionChange();
	//删除在线活动数据
	let ids = JsonArryToArray(activePhaseSelectLists,"id");
	if(ids.length>=0) {
		await service.campaign.stage.delete({ids});
		getActivityList();
	}
}
//打开活动属性
const activityModal=reactive({
	visible:false,
})
//引流数量改变
const activePhaseAttractionChange = () => {
	let attractionTargetValues = JsonArryToArray(activityParams.campaign_stage_list,"attraction_target");
	activityParams.attraction_target = attractionTargetValues.reduce((accumulator, currentValue)=>{
		return accumulator + currentValue;
	},0)
}
//新增阶段信息数据
const saveActiveRequest=(value:any)=>{
	if(value.id){
		return new Promise((resolve,reject)=>{
			service.campaign.stage.update(value).then(()=>{
				resolve(value);
			},(error)=>{
				reject(error);
			})
		});
	}else{
		return service.campaign.stage.add(value);
	}
}
const saveActivePhase=(value)=>{
	return new Promise((resolve,reject)=>{
		saveActiveRequest(value).then((result)=>{
			value.id = result.id;
			resolve(result);
		},(error)=>{
			reject(error);
		})
	})
}
const openActivityModal=(item?:any)=>{
	let value = {
		"id":"",
		"time":"",
		"copy_name": "",
		"content": "",
		"plan_id": "",
		"start_time": "",
		"end_time": "",
		"attraction_target": 0,
		"campaign_stage_list":<any>[],
	};
	Object.assign(activityParams, value);
	if(item){
		item.time = [dayjs(item.start_date),dayjs(item.end_date)];
	}
	Object.assign(activityParams,item);
	activityModal.visible = true;
}
const closeActivityModal=()=>{
	activityModal.visible = false;
}
const clusterTagParams=reactive({
	"inputs": {"no1":"","no2":"","no3":"","no4":"","no5":""},
	...config.AI_PARAMS
})
let planTagLoading = ref(false);
let addPlanTag:any = ref('');
let addPlanTagShow = ref(false);
const planTagLists:any=ref([]);
const getTagType = ():any => {
	const types=["primary","success","info","warning","danger"];
	let index = getRandomInt(5);
	return types[index];
}
const addPlanTagEvent = () => {
	if(!addPlanTag.value){
		ElMessage({
			message: "请输入客群标签",
			type: 'warning',
		})
		return;
	}
	let planTag = {value:addPlanTag.value,type:getTagType()};
	planTagLists.value.push(planTag);
	addPlanTag.value = "";
}
const deleteTag = (index) => {
	planTagLists.value.splice(index, 1);
}
const goOtherPageChange=(value:any,check?:Boolean)=>{
	if(check && planTagLists.value.length<=0){
		ElMessage({
			message: "还未输入客群标签",
			type: 'warning',
		})
		return true;
	}
	storage.set("planValue",{
		plan_id:queryParams.id,
		campaign_id:activityParams.id,
		stage_id:value.id,
		selectTag:route.query?.selectValue || "",
		startDate:route.query?.startDate || '',
		endDate:route.query?.endDate
	})
	return false;
}
const goAddPlaning = (value:any)=>{
	if(goOtherPageChange(value,true)){return};
	let planTags = planTagLists.value.map(item=> item.value);
	router.push({
		path:"/bespoke/add-planning",
		query:{
			answer:planTags.join("、")
		}
	});
}
//修改文章
const goArticle = (value:any)=>{
	if(goOtherPageChange(value)){return};
	router.push({
		path:"/work/planning/final-outline",
		query:{
			stage_id:value.id
		}
	});
}
const goEdit=(item)=>{
	console.log(item)
}
onMounted(()=>{
	storage.set("pageType","bespoke")
	searchPlanRequest(()=>{
		getActivityList()
	});
})
onActivated(() => {
	storage.set("pageType","bespoke")
})
</script>
<style scoped lang="scss">
.activity_dialog{
	width: 100%;
	overflow: hidden;
}
.input-1{
	width: 240px;
}
.view-title{
	&.width-1{
		width: 200px;
	}
	&--margin-1{
		margin: 40px auto;
	}
	&--margin-1-1{
		margin: 40px auto 0;
	}
	&--margin-2{
		margin: 40px auto 20px;
	}
	&--margin-2-1{
		margin-top: 40px;
	}
	&--margin-3{
		margin-top: 20px;
	}
	&--margin-3-1{
		margin: 20px auto;
	}
	text-indent: 10px;
	border-left:5px solid var(--el-color-primary);
	color: var(--el-text-color-primary);
	font-size: 18px;
	line-height: 24px;
	font-weight: 600;
	.view-title-option{
		font-size: 24px;
		padding: 2px;
	}
	&--clear-border{
		border-left:none;
	}
	&--clear-text-indent{
		text-indent: 0;
	}
}
.view-tag{
	width: 240px;
	overflow: hidden;
	margin: 0 auto;
	.view-tag-lists{
		min-height: 500px;
	}
}
.plan-planning-list{
	.plan-left{
		min-width: 340px;
	}
}
.vi-plan-lists{
	width: 100%;
	height: calc(100% - 230px);
	overflow: hidden;
	overflow-y: auto;
}
.timelineProcessBox {
	padding-top: 20px;
	.timelineProcessBox-border{
		border-bottom: 1px dashed #dddddd;
	}
	--list-timeline-width:200px;
	.timeline {
		display: flex;
		width: 100%;
		margin: 40px auto;
		padding-top: 30px;
		box-sizing: border-box;
		overflow: hidden;
		overflow-x: auto;
		.lineitem {
			width: --list-timeline-width;
			min-width: var(--list-timeline-width);
		}
	}
	:deep(.el-timeline-item__tail) {
		border-left: none;
		border-top: 2px solid #e4e7ed;
		width: 100%;
		position: absolute;
		top: 6px;
	}
	:deep(.el-timeline-item__tail),:deep(.el-timeline-item__node){
		left: calc(var(--list-timeline-width) / 2);
	}
	:deep(.el-timeline-item__wrapper) {
		padding-left: 0;
		padding-top: 20px;
		text-align: center;
		.timelineProcessBox-top-contents{
			position: absolute;
			left: 50%;
			top: -20px;
		}
	}
	:deep(.el-timeline-item__timestamp) {
		font-size: 14px;
	}
	.active {
		:deep(.el-timeline-item__node) {
			background-color: var(--el-color-primary);
		}
		:deep(.el-timeline-item__tail) {
			border-color: var(--el-color-primary);
		}
	}
	// 有active样式的下一个li
	.active + li {
		:deep(.el-timeline-item__node) {
			background-color: var(--el-color-primary);
		}
	}
	.timelineProcessBox-title{
		color:#333;
		font-size: 18px;
		line-height: 18px;
		cursor: pointer;
		&:hover{
			color: var(--el-color-primary);
		}
	}
	.timelineProcessBox-time,.timelineProcessBox-content{
		font-size: 14px;
		color: var(--el-text-color-secondary);
		line-height: 16px;
		margin-top: 10px;
	}
	.timelineProcessBox-top-contents,.timelineProcessBox-contents{
		width: 100%;
	}
	.timelineProcessBox-contents{
		display: flex;
		flex-direction: column;
	}
}
</style>
